package com.ihcy.base.config;

import com.alibaba.fastjson.JSON;
import com.ihcy.base.model.entity.User;
import com.ihcy.base.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 程序内部异步同步处理数据
 */
@Slf4j
@Component
public class ExecuteBatchUser implements CommandLineRunner {

    private final UserRepository userRepository;
    private final BlockingQueue<User> queue;
    private final AtomicLong start;
    private final int batchSize;
    // 毫秒
    private final int timeout;
    private final AtomicBoolean isLooping;

    public ExecuteBatchUser(UserRepository userRepository) {
        this.userRepository = userRepository;
        this.queue = new LinkedBlockingQueue<>();
        this.start = new AtomicLong(System.currentTimeMillis());
        this.batchSize = 10;
        this.timeout = 5000;
        this.isLooping = new AtomicBoolean(false);
    }

    @Override
    public void run(String... args) throws Exception {
//        while (true) {
//            long last = System.currentTimeMillis() - start.get();
//            if (isLooping.get() && (queue.size() > batchSize || (!queue.isEmpty() && last > timeout))) {
//                log.info("当前队列中条数{}--间隔时间{}", queue.size(), last);
//                List<User> users = new ArrayList<>();
//                int num = queue.drainTo(users, batchSize);
//                if (num > 0) {
//                    try {
//                        userRepository.saveAll(users);
//                    } catch (Exception e) {
//                        log.error("队列数据{}存储异常", JSON.toJSONString(users), e);
//                        this.queue.addAll(users);
//                    }
//                }
//                start.set(System.currentTimeMillis());
//            }
//        }
    }

    public boolean add(User user) {
        boolean result = this.queue.add(user);
        if (!isLooping.get()) {
            isLooping.set(true);
        }
        return result;
    }

    public boolean addBatch(List<User> users) {
        boolean result = this.queue.addAll(users);
        if (!isLooping.get()) {
            isLooping.set(true);
        }
        return result;
    }

    @PreDestroy
    public void detory() {
        System.out.println("关闭时，清理queue");
        if (!queue.isEmpty()) {
            List<User> users = new ArrayList<>();
            queue.drainTo(users);
            System.out.println("detory 剩余的user {" + JSON.toJSONString(users) + "}");
            userRepository.saveAll(users);
        }
    }

}
